<?php

namespace app\store\controller\content;

use app\store\controller\Controller;
use app\store\model\Video as VideoModel;
use app\store\service\order\Export as Exportservice;
/**
 * 视频
 * Class Video
 * @package app\store\controller\content
 */
class Video extends Controller
{
    
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function info($id)
    {
        // 查询问卷数据
        $Video = DB('Video_answer')->where('id', $id)->find();
        
        if (!$Video) {
            $this->error('问卷不存在');
        }

        // 获取并解析问卷内容
        $content = htmlspecialchars_decode($Video['answer_text']); // 解码 HTML 特殊字符
        $parsedContent = json_decode($content, true); // 将 JSON 字符串转换为数组

        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->error('问卷内容格式错误');
        }
        // dump($parsedContent);die;
        // 将问卷详情传递到模板
        return $this->fetch('info', [
            'Video' => $Video,
            'content' => $parsedContent,
        ]);
    }
    /**
     * 问卷列表
     */
    public function index()
    {
        $model = new VideoModel;
        $list = $model->getList(10,$this->request->param()); // 每页显示10条数据
        // dump($list);die;
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加视频
     * @return array|mixed
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }

        $data = $this->postData('video');
        $model = new VideoModel;

        // 检查是否上传了视频文件
        if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === 0) {
            $uploadedFile = $_FILES['video_file'];

            // 检查文件大小和类型
            $maxSize = 50 * 1024 * 1024; // 50MB
            $allowedExtensions = ['mp4', 'avi', 'mov', 'mkv'];

            $fileExtension = pathinfo($uploadedFile['name'], PATHINFO_EXTENSION);
            if (!in_array(strtolower($fileExtension), $allowedExtensions)) {
                return $this->renderError('仅支持以下视频格式：' . implode(', ', $allowedExtensions));
            }
            if ($uploadedFile['size'] > $maxSize) {
                return $this->renderError('视频文件大小不能超过50MB');
            }

            // 保存文件
            $uploadDir ='./uploads/videos/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $newFileName = uniqid() . '.' . $fileExtension;
            $filePath = $uploadDir . $newFileName;
            if (!move_uploaded_file($uploadedFile['tmp_name'], $filePath)) {
                return $this->renderError('视频上传失败，请重试');
            }

            // 设置视频URL为本地上传路径
            $domain = $this->request->domain();
            $data['video_url'] = $domain . '/uploads/videos/' . $newFileName;
        } elseif (empty($data['video_url'])) {
            // 如果没有上传文件也没有填写远程链接
            return $this->renderError('请上传视频文件或填写视频链接');
        }

        // 添加数据到数据库
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('content.video/index'));
        }

        return $this->renderError($model->getError() ?: '添加失败');
    }
    /**
     * 编辑视频
     * @param $id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $domain = request()->domain(); // 获取当前域名

        // 查询视频详情
        $model = VideoModel::alias('video')
            ->field([
                'video.*',
                'CONCAT("' . $domain . '/uploads/", uf.file_name) as video_img_url' // 拼接完整的图片 URL
            ])
            ->join('upload_file uf', 'video.video_img = uf.file_id', 'LEFT') // 关联 upload_file 表
            ->where('video.video_id', $id)
            ->find();

        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('model'));
        }

        $data = $this->postData('video');
        $videoFile = $this->request->file('video_file'); // 获取上传的视频文件

        // 处理视频文件上传逻辑
        if ($videoFile) {
            // 验证文件类型和大小
            $allowedExtensions = ['mp4', 'avi', 'mov', 'mkv'];
            $maxSize = 50 * 1024 * 1024; // 50MB
            $info = $videoFile->validate([
                'ext' => implode(',', $allowedExtensions),
                'size' => $maxSize,
            ])->move('./uploads/videos');

            if ($info) {
                // 成功上传后获取上传信息
                $data['video_url'] = $domain . '/uploads/videos/' . $info->getSaveName();
            } else {
                return $this->renderError($videoFile->getError());
            }
        } elseif (empty($data['video_url'])) {
            // 如果没有上传文件也没有填写远程链接，提示错误
            return $this->renderError('请上传视频文件或填写视频链接');
        }
        // dump($data);die;
        // 更新记录
        if ($model->edit($data)) {
            return $this->renderSuccess('更新成功', url('content.video/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
    /**
     * 删除
     * @param $article_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($id)
    {
        // 详情
        $model = VideoModel::where("video_id",$id)->find();
        // dump($model);die;
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
}